/**
 * Mock数据服务
 * 提供开发环境下的模拟数据支持
 */

import { config } from '@/config'
import userMock from './modules/user'
import habitsMock from './modules/habits'
import financeMock from './modules/finance'
import timeMock from './modules/time'
import todosMock from './modules/todos'
import statsMock from './modules/stats'
import settingsMock from './modules/settings'
import uploadMock from './modules/upload'

// Mock配置
const MOCK_CONFIG = {
  // 是否启用Mock
  enabled: config.debug && process.env.NODE_ENV === 'development',
  // 响应延迟时间（毫秒）
  delay: 300,
  // 成功率（0-1）
  successRate: 0.95,
  // 是否打印Mock日志
  log: true
}

// Mock数据模块
const mockModules = {
  ...userMock,
  ...habitsMock,
  ...financeMock,
  ...timeMock,
  ...todosMock,
  ...statsMock,
  ...settingsMock,
  ...uploadMock
}

/**
 * 模拟网络延迟
 * @param {number} delay 延迟时间
 */
function simulateDelay(delay = MOCK_CONFIG.delay) {
  return new Promise(resolve => {
    setTimeout(resolve, delay + Math.random() * 200)
  })
}

/**
 * 模拟网络错误
 * @param {number} successRate 成功率
 */
function simulateError(successRate = MOCK_CONFIG.successRate) {
  if (Math.random() > successRate) {
    const errors = [
      { code: 9999, message: '系统异常' },
      { code: 1003, message: '资源不存在' },
      { code: 1002, message: '未授权' },
      { code: 1004, message: '操作失败' }
    ]
    const error = errors[Math.floor(Math.random() * errors.length)]
    throw new Error(JSON.stringify(error))
  }
}

/**
 * 格式化响应数据
 * @param {any} data 响应数据
 * @param {string} message 响应消息
 * @param {number} code 响应码
 */
function formatResponse(data = null, message = 'success', code = 0) {
  return {
    code,
    message,
    data
  }
}

/**
 * 路径参数匹配
 * @param {string} pattern 路径模式（如 /habits/:id/history）
 * @param {string} path 实际路径（如 /habits/3/history）
 * @returns {object|null} 匹配结果，包含参数对象
 */
function matchPath(pattern, path) {
  const patternParts = pattern.split('/')
  const pathParts = path.split('/')
  
  if (patternParts.length !== pathParts.length) {
    return null
  }
  
  const params = {}
  
  for (let i = 0; i < patternParts.length; i++) {
    const patternPart = patternParts[i]
    const pathPart = pathParts[i]
    
    if (patternPart.startsWith(':')) {
      // 参数部分
      const paramName = patternPart.slice(1)
      params[paramName] = pathPart
    } else if (patternPart !== pathPart) {
      // 静态部分不匹配
      return null
    }
  }
  
  return { params }
}

/**
 * 查找匹配的Mock处理器
 * @param {string} method HTTP方法
 * @param {string} path 请求路径
 * @returns {object|null} 匹配结果
 */
function findMockHandler(method, path) {
  const exactKey = `${method} ${path}`
  
  // 首先尝试精确匹配
  if (mockModules[exactKey]) {
    return {
      handler: mockModules[exactKey],
      params: {},
      matchedKey: exactKey
    }
  }
  
  // 尝试参数化路径匹配
  for (const key in mockModules) {
    const [keyMethod, keyPath] = key.split(' ', 2)
    
    if (keyMethod === method && keyPath.includes(':')) {
      const matchResult = matchPath(keyPath, path)
      if (matchResult) {
        return {
          handler: mockModules[key],
          params: matchResult.params,
          matchedKey: key
        }
      }
    }
  }
  
  return null
}

/**
 * Mock请求处理器
 * @param {string} url 请求URL
 * @param {string} method 请求方法
 * @param {any} data 请求数据
 */
export async function mockRequest(url, method = 'GET', data = null) {
  // 如果未启用Mock，直接返回null
  if (!MOCK_CONFIG.enabled) {
    return null
  }

  // 标准化URL和方法
  let normalizedUrl = url.replace(/^\/api/, '')
  
  // 移除查询参数（如时间戳）
  let queryParams = {}
  if (normalizedUrl.includes('?')) {
    const [path, query] = normalizedUrl.split('?')
    normalizedUrl = path
    // 解析查询参数
    query.split('&').forEach(param => {
      const [key, value] = param.split('=')
      if (key && value !== undefined) {
        queryParams[decodeURIComponent(key)] = decodeURIComponent(value)
      }
    })
  }
  
  const normalizedMethod = method.toUpperCase()

  // 查找对应的Mock处理器
  const matchResult = findMockHandler(normalizedMethod, normalizedUrl)
  
  if (!matchResult) {
    if (MOCK_CONFIG.log) {
      console.warn(`[Mock] Mock数据未找到: ${normalizedMethod} ${url}`)
    }
    return null
  }
  
  const { handler: mockHandler, params: pathParams, matchedKey } = matchResult

  try {
    // 模拟网络延迟
    await simulateDelay()
    
    // 模拟网络错误
    simulateError()
    
    // 合并请求参数：路径参数、查询参数、请求体数据
    const requestParams = {
      ...queryParams,
      ...pathParams,
      ...(data || {})
    }
    
    // 执行Mock处理器
    const result = await mockHandler(requestParams, { 
      url, 
      method, 
      pathParams, 
      queryParams,
      originalUrl: url
    })
    
    // 格式化响应
    const response = formatResponse(result)
    
    if (MOCK_CONFIG.log) {
      console.log(`[Mock] ${matchedKey}:`, response)
    }
    
    return response
  } catch (error) {
    if (MOCK_CONFIG.log) {
      console.error(`[Mock] ${matchedKey} 错误:`, error)
    }
    
    // 解析错误信息
    let errorInfo
    try {
      errorInfo = JSON.parse(error.message)
    } catch {
      errorInfo = { code: 9999, message: error.message || '系统异常' }
    }
    
    throw new Error(JSON.stringify(formatResponse(null, errorInfo.message, errorInfo.code)))
  }
}

/**
 * 设置Mock配置
 * @param {object} config Mock配置
 */
export function setMockConfig(config) {
  Object.assign(MOCK_CONFIG, config)
}

/**
 * 获取Mock配置
 */
export function getMockConfig() {
  return { ...MOCK_CONFIG }
}

/**
 * 添加Mock处理器
 * @param {string} key Mock键名
 * @param {function} handler Mock处理器
 */
export function addMockHandler(key, handler) {
  mockModules[key] = handler
}

/**
 * 移除Mock处理器
 * @param {string} key Mock键名
 */
export function removeMockHandler(key) {
  delete mockModules[key]
}

/**
 * 获取所有Mock处理器
 */
export function getAllMockHandlers() {
  return { ...mockModules }
}

export default {
  mockRequest,
  setMockConfig,
  getMockConfig,
  addMockHandler,
  removeMockHandler,
  getAllMockHandlers
}